package cz.muni.fi.pa165.rentalofconstructionmachinery.dao.impl;

import cz.muni.fi.pa165.rentalofconstructionmachinery.dao.MachineDAO;
import cz.muni.fi.pa165.rentalofconstructionmachinery.entity.Machine;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;

/**
 *
 * @author Zuzana Krejcova
 */
@Repository(value = "machineDao")
public class MachineDAOImpl implements MachineDAO {
    
    private static final Logger logger = LoggerFactory.getLogger(MachineDAOImpl.class);
    
    @PersistenceContext
    private EntityManager entityManager;

    @Override
    public void createMachine(Machine machine) {
        if (machine == null) {
            throw new IllegalArgumentException("Argument machine cannot be null.");
        }
        if (machine.getLicensePlate() == null) {
            throw new IllegalArgumentException("The machine must have a license plate, it is null now.");
        }
        logger.debug("Trying to create a new Machine in DB: {}", machine);
        entityManager.persist(machine);
    }

    @Override
    public void deleteMachine(Machine machine) {
        if (machine == null) {
            throw new IllegalArgumentException("Argument machine cannot be null.");
        }
        logger.debug("Trying to delete a Machine in DB: {}", machine);
        entityManager.remove(entityManager.merge(machine));
    }

    @Override
    public void updateMachine(Machine machine) {
        if (machine == null) {
            throw new IllegalArgumentException("Argument machine cannot be null.");
        }
        logger.debug("Trying to update a Machine in DB: {}", machine);
        entityManager.merge(machine);
    }

    @Override
    public List<Machine> getAllMachines() {
        logger.debug("Getting all Machines from DB.");
        List<Machine> results = entityManager.createQuery("select m from Machine m", Machine.class).getResultList();
        return results;
    }

    @Override
    public Machine getMachineById(Long id) {
        if (id == null) {
            throw new IllegalArgumentException("Argument id cannot be null.");
        }
        logger.debug("Getting a Machine from DB, id: {}", id);
        Machine result = entityManager.createQuery("select m from Machine m where m.id=" + id, Machine.class).getSingleResult();
        return result;
    }
}